<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理系统</title>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入Vue和Element UI JS -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- 引入axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        body {
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f7fa;
        }
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .search-box {
            margin-bottom: 20px;
            display: flex;
        }
        .search-box .el-input {
            width: 300px;
            margin-right: 10px;
        }
        .pagination {
            margin-top: 20px;
            text-align: center;
        }
        .el-table {
            margin-top: 20px;
        }
        .user-id {
            font-family: monospace;
            white-space: nowrap;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="container">
        <h2 style="margin-bottom: 20px;">用户管理系统</h2>

        <!-- 搜索框和添加按钮 -->
        <div class="search-box">
            <el-input
                    v-model="searchQuery"
                    placeholder="请输入ID、用户名或邮箱"
                    clearable
                    @clear="handleSearch"
                    @keyup.enter.native="handleSearch"
            >
                <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
            <el-button type="primary" @click="showAddDialog">添加用户</el-button>
        </div>

        <!-- 用户表格 -->
        <el-table :data="processedUserList" border style="width: 100%">
            <el-table-column prop="useridStr" label="用户ID" width="200">
                <template slot-scope="scope">
                    <span class="user-id">{{ scope.row.useridStr }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="username" label="用户名" width="150"></el-table-column>
            <el-table-column prop="password" label="密码" width="150"></el-table-column>
            <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
            <el-table-column prop="createdDt" label="创建时间" width="180">
                <template slot-scope="scope">
                    {{ formatDate(scope.row.createdDt) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.row.userid)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-size="pageSize"
                    :total="total"
                    layout="prev, pager, next, jumper"
                    :pager-count="5"
            ></el-pagination>
        </div>

        <!-- 添加/编辑用户对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
            <el-form :model="userForm" :rules="rules" ref="userForm" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="userForm.password" show-password></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                userList: [], // 原始用户数据
                processedUserList: [], // 处理后的用户数据（包含字符串ID）
                currentPage: 1,
                pageSize: 10,
                total: 0,
                searchQuery: '',
                dialogVisible: false,
                dialogTitle: '添加用户',
                userForm: {
                    userid: null,
                    username: '',
                    password: '',
                    email: ''
                },
                rules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ]
                }
            }
        },
        created() {
            this.fetchUsers();
        },
        methods: {
            // 处理用户数据，将ID转为字符串
            processUserData(users) {
                return users.map(user => {
                    return {
                        ...user,
                        useridStr: user.userid.toString(), // 添加字符串形式的ID
                        // 保留原始ID用于操作
                        userid: user.userid
                    };
                });
            },

            formatDate(dateStr) {
                if (!dateStr) return '';
                const date = new Date(dateStr);
                return date.toLocaleString();
            },

            fetchUsers() {
                if (this.searchQuery) {
                    this.searchUsers();
                } else {
                    axios.post('/user/findPage', { pageNumber: this.currentPage }, {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    })
                        .then(response => {
                            this.userList = response.data;
                            this.processedUserList = this.processUserData(response.data);
                        })
                        .catch(error => {
                            this.$message.error('获取用户数据失败');
                            console.error(error);
                        });
                }
            },

            searchUsers() {
                const query = this.searchQuery.trim();
                if (!query) {
                    this.fetchUsers();
                    return;
                }

                if (/^\d+$/.test(query)) {
                    // 处理大数字ID查询
                    axios.post('/user/findByUserid', query, {
                        headers: {
                            'Content-Type': 'text/plain'
                        },
                        transformRequest: [function(data) {
                            return data;
                        }]
                    })
                        .then(response => {
                            const data = response.data ? [response.data] : [];
                            this.userList = data;
                            this.processedUserList = this.processUserData(data);
                            this.total = this.userList.length;
                        })
                        .catch(error => {
                            this.$message.error('查询失败');
                            console.error(error);
                        });
                } else if (query.includes('@')) {
                    axios.post('/user/findByEmail', query, {
                        headers: {
                            'Content-Type': 'text/plain'
                        },
                        transformRequest: [function(data) {
                            return data;
                        }]
                    })
                        .then(response => {
                            const data = response.data ? [response.data] : [];
                            this.userList = data;
                            this.processedUserList = this.processUserData(data);
                            this.total = this.userList.length;
                        })
                        .catch(error => {
                            this.$message.error('查询失败');
                            console.error(error);
                        });
                } else {
                    axios.post('/user/findByUsername', query, {
                        headers: {
                            'Content-Type': 'text/plain'
                        },
                        transformRequest: [function(data) {
                            return data;
                        }]
                    })
                        .then(response => {
                            const data = response.data ? [response.data] : [];
                            this.userList = data;
                            this.processedUserList = this.processUserData(data);
                            this.total = this.userList.length;
                        })
                        .catch(error => {
                            this.$message.error('查询失败');
                            console.error(error);
                        });
                }
            },

            handleSearch() {
                this.currentPage = 1;
                this.fetchUsers();
            },

            handleCurrentChange(page) {
                this.currentPage = page;
                this.fetchUsers();
            },

            showAddDialog() {
                this.dialogTitle = '添加用户';
                this.userForm = {
                    userid: null,
                    username: '',
                    password: '',
                    email: ''
                };
                this.dialogVisible = true;
                this.$nextTick(() => {
                    this.$refs.userForm.clearValidate();
                });
            },

            handleEdit(row) {
                this.dialogTitle = '编辑用户';
                this.userForm = {
                    userid: row.userid, // 使用原始ID
                    username: row.username,
                    password: row.password,
                    email: row.email
                };
                this.dialogVisible = true;
            },

            submitForm() {
                this.$refs.userForm.validate(valid => {
                    if (valid) {
                        if (this.userForm.userid) {
                            // 确保userid作为字符串传递，避免精度丢失
                            const data = {
                                ...this.userForm,
                                userid: this.userForm.userid.toString()
                            };
                            axios.post('/user/updateUser', data)
                                .then(response => {
                                    this.$message.success('用户更新成功');
                                    this.dialogVisible = false;
                                    this.fetchUsers();
                                })
                                .catch(error => {
                                    this.$message.error('用户更新失败');
                                    console.error(error);
                                });
                        } else {
                            axios.post('/user/insertUser', this.userForm)
                                .then(response => {
                                    this.$message.success('用户添加成功');
                                    this.dialogVisible = false;
                                    this.fetchUsers();
                                })
                                .catch(error => {
                                    this.$message.error('用户添加失败');
                                    console.error(error);
                                });
                        }
                    }
                });
            },

            handleDelete(userid) {
                this.$confirm('确认删除该用户吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 确保userid作为字符串传递
                    axios.post('/user/deleteUser', userid.toString(), {
                        headers: {
                            'Content-Type': 'text/plain'
                        },
                        transformRequest: [function(data) {
                            return data;
                        }]
                    })
                        .then(response => {
                            this.$message.success('删除成功');
                            this.fetchUsers();
                        })
                        .catch(error => {
                            this.$message.error('删除失败');
                            console.error(error);
                        });
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            }
        }
    });
</script>
</body>
</html>